<?php
include 'checkLogin.php';

@$id = $_REQUEST['id'];
@$name = $_REQUEST['name'];

if(empty($id)){
	echo json_encode(array('status'=>false,'info'=>'发送数据失败'));
	die;
}

include 'db/li.php';

if($name == "type"){
	@$goods = dbSelectAll('select goods.id from goods join type on goods.typeId=type.id where goods.typeId=:id',array('id'=>$id));
	if(empty($goods)){
		flog($id);
	}else{
		foreach ($goods as $good){
			@$goods_orders = dbSelectAll('select goodsId,orderId from goods_order where goodsId=:id',array('id'=>$good['id']));
			if(empty($goods_orders)){
				flog($id);
			}else{
				echo json_encode(array('status'=>false,'info'=>'删除失败,此类型下已有商品被订购'));
				die;
			}
		}
	}
}

if($name == "goods"){
	@$goods_orders = dbSelectAll('select goodsId,orderId from goods_order where goodsId=:id',array('id'=>$id));
	
	if(empty($goods_orders)){
		@$flog = dbDelete('delete from goods where id=:id',array('id'=>$id));
		if(!$flog){
			echo json_encode(array('status'=>false,'info'=>'删除失败'));
			die;
		}
	}else{
		echo json_encode(array('status'=>false,'info'=>'删除失败,此商品已被订购'));
		die;
	}
}

if($name == "order"){
	@$goodsCounts = dbSelectAll('select goodsId from goods_order where orderId=:oid',array('oid'=>$id));
	foreach($goodsCounts as $goodsCount){
		@$goods = dbSelect("select count from goods_order where goodsId=:id and orderId=:oid",
							array('id'=>$goodsCount['goodsId'],'oid'=>$id));					//还原库存    状态
		@$flog = dbUpdate("update goods set stock=stock+:count,sellStatus='上架' where id=:id",
							array('count'=>$goods['count'],'id'=>$goodsCount['goodsId']));
		if(!$flog){
			echo json_encode(array('status'=>false,'info'=>'还原库存失败'));
			die;
		}
	}
	@$flog = dbDelete('delete from goods_order where goods_order.orderId=:id;
						delete from `order` where id=:id',array('id'=>$id));			//删除订单
	if(!$flog){
		echo json_encode(array('status'=>false,'info'=>'删除失败'));
		die;
	}
}
function flog($id){
	@$flog = dbDelete('delete from goods where typeId=:id;
						delete from type where id=:id',array('id'=>$id));
	if(!$flog){
		echo json_encode(array('status'=>false,'info'=>'删除失败'));
		die;
	}
}

if($name == "worker"){											//删除职员
	@$flog = dbDelete('delete from worker where id=:id',array('id'=>$id));
	if(!$flog){
		echo json_encode(array('status'=>false,'info'=>'删除失败'));
		die;
	}
}
if($name == "role"){											//删除职位
	//@$userId = $_SESSION['userId'];
	@$flog = dbDelete('delete from worker where roleId=:id;
						delete from `user` where roleId=:id;
						delete from role where id=:id',array('id'=>$id));
	if(!$flog){
		echo json_encode(array('status'=>false,'info'=>'删除失败'));
		die;
	}
}

echo json_encode(array('status'=>true,'$name'=>$name,'$id'=>$id));








